import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:inspiration_f/model/home_mode.dart';
import 'package:inspiration_f/page/home/home_controller.dart';
import 'package:inspiration_f/page/home/home_item.dart';
import 'package:inspiration_f/page/home/home_manager.dart';
import 'package:inspiration_f/utils/color.dart';
import 'package:inspiration_f/utils/size.dart';
import 'package:inspiration_f/utils/xm_preferences.dart';
import 'package:inspiration_f/view/home_dialog.dart';

// 首页
class HomePage extends StatefulWidget {
  // 导航栏高度
  double naviHeight = 0;
  HomeController homeController = HomeController();

  HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  bool showHomeDialog = false;
  HomeModel? currentModel;
  TextEditingController controller = TextEditingController();
  ScrollController scrollController = ScrollController();
  AnimationController? _animationController;
  HomeDialog? homeView;
  double safeBottom = 0;

  // 添加数据 - 弹出
  _addAction() {
    print("_addAction");
    HomeManager.instance.startTop = widget.naviHeight + 20;
    var nowTime = DateTime.now().toString();
    currentModel =
        HomeModel(id: nowTime, title: "", colorInt: Random().nextInt(4));
    setState(() {
      showHomeDialog = true;
    });
  }

  // 更新数据 - 弹出
  _updateAction() {
    print("_updateAction");
    homeView?.isShowing = false;
    setState(() {
      showHomeDialog = true;
    });
  }

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 1000))
      ..repeat(reverse: true);
    if (homeView == null) {
      homeView =
          HomeDialog(this.currentModel, this.controller, widget.homeController);
      homeView?.clickSaveTap = () {
        homeView?.dialogStatus = HomeDialogStatus.closed;
        setState(() {
          showHomeDialog = false;
        });
      };
    }
  }

  @override
  Widget build(BuildContext context) {
    widget.naviHeight = MediaQuery.of(context).padding.top + 44;
    safeBottom = MediaQuery.of(context).padding.bottom + 16;
    print("init=，，${widget.naviHeight}=======${showHomeDialog}");
    if (XMPreferences.instance.sharePreInstance == null) {
      // 需要重新初始化
      Future.delayed(const Duration(milliseconds: 500)).then((value) {
        setState(() {});
      });
    }
    return Stack(
      children: [
        _normalHomeWidget(),
        showHomeDialog
            ? _homeDialogWidget()
            : const SizedBox(width: 0, height: 0)
      ],
    );
  }

  _homeDialogWidget() {
    homeView?.homeM = currentModel;
    if (homeView?.dialogStatus == HomeDialogStatus.closed) {
      homeView?.showAction(currentModel);
    }
    return homeView;
  }

  _normalHomeWidget() {
    return Scaffold(
      resizeToAvoidBottomInset: false, // 不跟随键盘移动
      backgroundColor: xmBgColor,
      appBar: AppBar(
        title: const Align(
            alignment: Alignment.center,
            child: Text("灵感胶囊", style: TextStyle(fontWeight: FontWeight.w500))),
      ),
      body: Stack(
        children: [
          SlidableAutoCloseBehavior(
            // 允许一行进行滑动删除
            child: ReorderableListView.builder(
              onReorder: (oldIndex, newIndex) {
                if (oldIndex < newIndex) {
                  newIndex -= 1;
                }
                XMPreferences().localModelArr.insert(
                    newIndex, XMPreferences().localModelArr.removeAt(oldIndex));
                XMPreferences().refreshLocalData();
                setState(() {});
              },
              itemCount: XMPreferences().localModelArr.length,
              scrollController: scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.only(
                  top: 6, bottom: MediaQuery.of(context).padding.bottom + 86),
              itemBuilder: (context, index) {
                List<HomeModel>? modelList = XMPreferences().localModelArr;
                if (modelList!.length > index) {
                  var model = modelList?[index];
                  var homeItem = HomeItem(currentModel: model);
                  homeItem.clickAction = () {
                    HomeManager.instance.startTop = widget.naviHeight +
                        index * (homeItemHeight + 8) +
                        16 +
                        4 -
                        scrollController.offset;
                    currentModel = model;
                    _updateAction();
                  };
                  return Padding(
                    key: ValueKey(index),
                    padding: const EdgeInsets.only(
                        left: 16, right: 16, top: 4, bottom: 4),
                    child: Slidable(
                      // controller: _slidableController,
                      child: homeItem,
                      key: ValueKey(index),
                      endActionPane: ActionPane(
                        motion: const StretchMotion(), // 滑动出来的模式
                        children: [
                          SlidableAction(
                            flex: 2,
                            borderRadius:
                                const BorderRadius.all(Radius.circular(30)),
                            // borderRadius: const BorderRadius.only(
                            //     topRight: Radius.circular(30),
                            //     bottomRight: Radius.circular(30)),
                            spacing: 5, // icon和label的间隙
                            onPressed: (context) {
                              Slidable.of(context)?.close();
                              setState(() {
                                XMPreferences.instance.removeHomeModel(model);
                              });
                            },
                            backgroundColor: xmRed,
                            foregroundColor: Colors.white,
                            label: "删除",
                            icon: Icons.delete,
                            autoClose: false,
                          ),
                        ],
                      ),
                    ),
                  );
                } else {
                  return SizedBox();
                }
              },
            ),
          ),
          AnimatedBuilder(
            animation: _animationController!,
            builder: (BuildContext context, Widget? child) {
              return Align(
                alignment: Alignment.bottomRight,
                child: Container(
                  margin: EdgeInsets.only(right: 16, bottom: safeBottom),
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: xmPrimaryColor,
                      gradient: RadialGradient(
                        colors: [
                          xmPrimaryColor.withOpacity(0.8),
                          xmPrimaryColor.withOpacity(0.3)
                        ],
                        stops: [
                          0.1 + _animationController!.value,
                          1.0 + _animationController!.value
                        ],
                        // stops: [0.1, 1.0],
                      )),
                  child: InkWell(
                    onTap: _addAction,
                    highlightColor: Colors.transparent,
                    splashColor: xmBgColor,
                    child: Icon(
                      size: 15 * _animationController!.value + 5,
                      Icons.add,
                      color: Colors.white,
                    ),
                  ),
                ),
              );
            },
          )
        ],
      ),
    );
  }
}
